#!/usr/bin/python3
#******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
"""
This is a helper script for working with gitee.com
"""

import sys
import os
import json
import base64
import urllib
import urllib.request
import urllib.parse
import urllib.error


class Gitee():
    """
    Gitee is a helper class to abstract gitee.com api
    """
    def __init__(self):
        #self.secret = open(os.path.expanduser("~/.gitee_personal_token.json"), "r")
        self.token = {}
        with open(os.path.expanduser("~/.gitee_token.json"), "r") as f:
            self.token = json.load(f)

        self.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW 64; rv:50.0) '\
                        'Gecko/20100101 Firefox/50.0'}

    def post_gitee(self, url, values, headers=None):
        """
        POST into gitee API
        """
        if headers is None:
            headers = self.headers.copy()
        data = urllib.parse.urlencode(values).encode('utf-8')
        req = urllib.request.Request(url=url, data=data, headers=headers, method="POST")
        try:
            result = urllib.request.urlopen(req)
            return result.read().decode("utf-8")
        except urllib.error.HTTPError as err:
            print("WARNING:" + str(err.code))
            print("WARNING:" + str(err.headers))
            return False

    def get_gitee(self, url, headers=None):
        """
        GET from gitee api
        """
        if headers is None:
            req = urllib.request.Request(url=url, headers=self.headers)
        else:
            req = urllib.request.Request(url=url, headers=headers)
        try:
            result = urllib.request.urlopen(req)
            return result.read().decode("utf-8")
        except urllib.error.HTTPError as e:
            print(url)
            print(str(e.code) + " " + e.reason)
            return None
        except urllib.error.URLError as e:
            print(url)
            print(e.reason)
            return None

    def get_reviewers(self, repo, owner="src-openeuler"):
        """
        Get reviewers of pkg
        """
        url_template = "https://gitee.com/api/v5/repos/{owner}/{pkg}/collaborators"
        url = url_template.format(owner=owner, pkg=repo)
        return self.get_gitee_dict(url)

    def get_gitee_json(self, url):
        """
        Get and load gitee json response
        """
        json_resp = []
        headers = self.headers.copy()
        headers["Content-Type"] = "application/json;charset=UTF-8"
        resp = self.get_gitee(url, headers)
        if resp:
            json_resp = json.loads(resp)
        return json_resp

    def get_gitee_dict(self, url, param=""):
        url += param
        token_param = "access_token={}".format(self.token["access_token"])
        separator = "?"
        if param:
            separator = "&"
        url += separator + token_param
        return self.get_gitee_json(url)

    def get_contributors(self, repo, owner):
        """
        Get contributors of owner/repo
        """
        url_template = "https://gitee.com/api/v5/repos/{owner}/{repo}/contributors"
        url = url_template.format(owner=owner, repo=repo)
        return self.get_gitee_dict(url)

    def get_branches(self, repo, owner):
        """
        Get branches of owner/repo
        """
        url_template = "https://gitee.com/api/v5/repos/{owner}/{repo}/branches"
        url = url_template.format(owner=owner, repo=repo)
        return self.get_gitee_dict(url)

    def get_commits(self, repo, owner, sha="", author="", since="", until="", page=1, per_page=20):
        """
        Get commits of owner/repo
        """
        url_template = "https://gitee.com/api/v5/repos/{owner}/{repo}/commits"
        url = url_template.format(owner=owner, repo=repo)
        param = "?page={}&per_page={}".format(page, per_page)
        if sha:
            param += "&sha={}".format(sha)
        if author:
            param += "&author={}".format(author)
        if since:
            param += "&since={}".format(since)
        if until:
            param += "&until={}".format(until)
        return self.get_gitee_dict(url, param)

    def get_one_commit(self, repo, sha, owner):
        """
        Get one commit of owner/repo
        """
        url_template = "https://gitee.com/api/v5/repos/{owner}/{repo}/commits/{sha}"
        url = url_template.format(owner=owner, repo=repo, sha=sha)
        return self.get_gitee_dict(url)

    def get_pr_list(self, repo, owner, head="", base="", state="all", page=1, per_page=20):
        """
        Get PR list of owner/repo
        """
        url_template = "https://gitee.com/api/v5/repos/{owner}/{repo}/pulls"
        url = url_template.format(owner=owner, repo=repo)
        param = "?state={}&sort=created&direction=desc&page={}&per_page={}".format(state, page, per_page)
        if head:
            param += "&head={}".format(head)
        if base:
            param += "&base={}".format(base)
        return self.get_gitee_dict(url, param)

    def get_pr_comments(self, repo, number, owner, page=1, per_page=20):
        """
        Get PR comments of owner/repo
        """
        url_template = "https://gitee.com/api/v5/repos/{owner}/{repo}/pulls/{number}/comments"
        url = url_template.format(owner=owner, repo=repo, number=number)
        param = "?page={}&per_page={}".format(page, per_page)
        return self.get_gitee_dict(url, param)

    def get_repos(self, org, repo_type, page=1, per_page=20):
        """
        Get repos of org
        """
        url_template = "https://gitee.com/api/v5/orgs/{org}/repos"
        url = url_template.format(org=org)
        param = "?type={}&page={}&per_page={}".format(repo_type, page, per_page)
        return self.get_gitee_dict(url, param)


if __name__ == "__main__":
    pass
